<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use Qiniu\Storage\BucketManager;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    /**
     * 配置七牛云
     * @return string
     */
    public function initQiNiu(){

        $accessKey = config('qiniu.AK');
        $secretKey = config('qiniu.SK');
        //初始化Auth状态
        return new Auth($accessKey, $secretKey);
    }

    /**
     * 七牛云文件上传
     * @param $key
     * @param $filePath
     * @throws \Exception
     */
    public function QiNiuUploadFile($key,$filePath){

        $auth = $this->initQiNiu();
        $token = $auth->uploadToken(config('qiniu.bucket'));
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        return $uploadMgr->putFile($token,$key,$filePath,null,'application/octet-stream', true, null, 'v2');
    }

    /**
     * 七牛云文件删除
     * @param $key
     */
    public function QiNiuDelFile($key){
        $auth = $this->initQiNiu();
        $config = new \Qiniu\Config();
        $bucketManager = new BucketManager($auth, $config);
        $bucketManager->delete(config('qiniu.bucket'), $key);
    }

    /**
     * 判断七牛云是否存在该文件
     * @param $key
     * @return bool
     */
    public function isExistFileOnQiNiu($key){
        $auth = $this->initQiNiu();
        $config = new \Qiniu\Config();
        $bucketManager = new BucketManager($auth, $config);
        $res = $bucketManager->stat(config('qiniu.bucket'), $key);

        if(!$res[0]){
            return false;
        }else{
            return true;
        }
    }

    public function initRedis($select = 0 ){
        $redis = new \Redis();
        $redis->connect(env("REDIS_HOST"),env("REDIS_PORT"));
        $redis->select($select);
        return $redis;
    }

    /**
     * 使用AK&SK初始化蓝队云账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public function createLanDuiClient(){
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => 'bGRha2IzMjE0YjRjOWZlOWNhMDgzYjlk',
            // 您的 AccessKey Secret
            "accessKeySecret" => 'bGRzazVlODRhN2YzYmNjZDdjMGE0ODk3'
        ]);
        $config->endpoint = "apisms.landui.com";
        return new Dysmsapi($config);
    }


    /**
     * 通过蓝队云发送验证码
     */
    public function sendAuthCode($phone){
        $client = $this->createLanDuiClient();

        //随机生成6位的验证码
        $code = mt_rand(100000,999999);

        //redis保存验证码
        $this->initRedis()->sadd($phone,$code);
        $this->initRedis()->expire($phone,300);

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => "PShape小程序",
            "templateCode" => "1664",
            "templateParam" => "{\"code\":\"$code\"}"
        ]);

        $runtime = new RuntimeOptions([]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        } catch (\Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // 如有需要，请打印 error
            Utils::assertAsString($error->message);
        }
    }

    /**
     * 如果返回的数据中有null则修改为空
     * @param $data
     */
    private function parseNull(&$data){
        if(is_array($data)){
            foreach($data as &$v){
                $this->parseNull($v);
            }
        } else {
            if (null === $data){
                $data = "";
            }
        }
    }

    /**
     * 接口成功返回
     * @param $data
     * @param string $msg
     * @return mixed
     */
    public function success($data,$msg="success"){
        $this->parseNull($data);
        $result = [
            "code" => 200,
            "msg" => $msg,
            "data" => $data
        ];
        return response()->json($result,200);
    }

    /**
     * 接口错误返回
     * @param string $code
     * @param string $msg
     * @return \Illuminate\Http\JsonResponse
     */
    public function error($code='5000', $msg = "failure"){
        $result = [
            "code" => $code,
            "msg" => $msg,
        ];

        return response()->json($result,200);
    }

    /**
     * 模拟post方式进行网络请求
     */
    public function postReqByCurl(){

    }

    /**
     * 模拟get方式进行网络请求
     */
    public function getReqByCurl($url){
        $headerArray =array("Content-type:application/json;","Accept:*/*");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);

        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    /**
     * 查询后的数据转换为一维数组 ==
     * @param array $arr
     * @param string $field
     * @return array
     */
    public function toLinearArray($arr=[],$field=''){
        $linearArr=[];
        foreach($arr as $k=>$v){
            $linearArr[]=$v[$field];
        }
        return $linearArr;
    }

    /**
     * 获取随机数字组合
     * @param int $length
     * @return string
     */
    public function getRandStr($length = 6){
        $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $len = strlen($str)-1;
        $randStr = '';
        for ($i=0;$i<$length;$i++) {
            $num=mt_rand(0,$len);
            $randStr .= $str[$num];
        }
        return $randStr;
    }

}
